package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type UserList struct {
	Users []User `json:"users"`
}

type User struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Age    int    `json:"age"`
	Social Social `json:"social"`
}

type Social struct {
	Facebook string `json:"facebook"`
	Twitter  string `json:"twitter"`
}

var str string = `{
  "users": [
    {
      "name": "Elliot",
      "type": "Reader",
      "age": 23,
      "social": {
        "facebook": "https://facebook.com",
        "twitter": "https://twitter.com"
      }
    },
    {
      "name": "Fraser",
      "type": "Author",
      "age": 17,
      "social": {
        "facebook": "https://facebook.com",
        "twitter": "https://twitter.com"
      }
    }
  ]
}
`

func writeToFile(filepath string, data string) error {
	f, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = f.WriteString(str)
	if err != nil {
		return err
	}
	return nil
}

func readFromFile(filepath string) (string, error) {
	bdata, err := ioutil.ReadFile(filepath)
	if err != nil {
		return "", err
	}
	sdata := string(bdata[:])
	return sdata, nil
}

func main() {
	err := writeToFile("users.json", str)
	if err != nil {
		panic(err)
	}
	data, err := readFromFile("users.json")
	if err != nil {
		panic(err)
	}
	fmt.Println("Successfully opened users.json")
	var userList UserList

	err = json.Unmarshal([]byte(data), &userList)
	if err != nil {
		panic(err)
	}

	for _, user := range userList.Users {
		fmt.Println("User Type: ", user.Type)
		fmt.Println("User Age: ", user.Age)
		fmt.Println("User Name: ", user.Name)
		fmt.Println("Facebook Url: ", user.Social.Facebook)
	}

	fmt.Println(userList)

}
